package com.sduept.nwld.wave.rest;

import com.alibaba.fastjson.JSONObject;
import com.sduept.core.dao.SuperDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 直流分量数据REST服务
 * @author Ningfw
 * @date 2017-06-23
 *
 */
@RestController
@RequestMapping("/decay/")
public class DecayServices {

	@Autowired
	private SuperDAO superDao;
	

	@GetMapping("/getDecay/{fileId}/{lineId}")
	public String getDecay(@PathVariable("fileId") String fileId,@PathVariable("lineId") String lineId){
		
		JSONObject jso = new JSONObject();
		JSONObject jso2 = new JSONObject();
		
		StringBuffer postFaultSb = new StringBuffer();//查询全部直流分量sql字段
		StringBuffer xAxisSb = new StringBuffer();//查询全部直流分量sql列简化后的名称，作为x轴
		for(int i=0; i <= 180; i = i+5){
			postFaultSb.append(",post_fault_init_value_"+i).append(","+("post_fault_time_value_"+i));
			xAxisSb.append(","+i+"ms");
		}
		
		String[] xArr = (xAxisSb.toString().substring(1)).split(",");//x轴
		String sqlStr = postFaultSb.toString();
		String sqlDecay = "SELECT phase_type"+sqlStr+" FROM t_lbtz_line_dc_decay ld WHERE ld.fault_file_id = '"+fileId+"' "
			+ "AND ld.line_id = '"+lineId+"'";
		List<?> listDecay = superDao.nativeQuery(sqlDecay);
		
		for(Object obj : listDecay){
			List<String> initList = new ArrayList<String>();//故障后*ms直流初始值
			List<String> timeList = new ArrayList<String>();//故障后*ms衰减时间常数
			Object[] objArr = (Object[])obj;
			Object[] objType = Arrays.copyOf(objArr, 1);//相别
			Object[] objs = Arrays.copyOfRange(objArr, 1, objArr.length);//数据
			for(int i=0; i < objs.length; i++){
				if(i%2 == 0){//*ms直流初始值
					initList.add(keepBit(objs[i].toString()));
				}else{//*ms衰减时间常数
					timeList.add(keepBit(objs[i].toString()));
				}
			}
			
			JSONObject decayObj = new JSONObject();//存放每一条数据的直流初始值和衰减时间常数
			decayObj.put("init", initList);
			decayObj.put("time", timeList);
			
			String decay;//键
			decay = objType[0].toString();
			jso.put(decay, decayObj);//数据
		}
		
		jso2.put("xAxis", xArr);//x轴
		jso2.put("series", jso);
		return jso2.toJSONString();
	}
	
	/**
	 * 保留三位小数
	 * @param str
	 * @return
	 */
	public String keepBit(String str){
		if(null != str && !"".equals(str)){
			BigDecimal bd = new BigDecimal(str);
			String res = bd.setScale(3, BigDecimal.ROUND_HALF_UP).toString();
			return res;
		}else{
			return null;
		}
	}
}
